package com.yeung.actions;

import com.yeung.beans.Employee;
import com.yeung.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class DataConvertTest {
    @Autowired
    private EmployeeDao employeeDao;

    /**
     * @return
     * @ResponseBody 注解 告诉spring返回的数据为json格式
     */
    @RequestMapping("/json")
    @ResponseBody
    public Employee jsonTest() {
        return employeeDao.getEmployeeById(1001);
    }

    //模拟下载功能
    @RequestMapping("/testResponseEntity")
    public ResponseEntity<byte[]> testResponseEntity(HttpServletRequest request) throws IOException {
        ServletContext context = request.getServletContext();
        System.out.println(request.getServletContext().getContextPath());
        InputStream in = context.getResourceAsStream("files/abc.txt");
        byte[] body = new byte[in.available()];
        in.read(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Disposition", "attachment;filename=abc.txt");
        HttpStatus statusCode = HttpStatus.OK;

        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(body, headers, statusCode);
        return responseEntity;
    }


}
